/*
 * @Author: Aro
 * @Date: 2024-01-21 13:45:32
 */
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_baseui/routers/fluro_navigator.dart';
import 'package:flutter_baseui/utils/screen_util.dart';
import 'package:flutter_baseui/views/home_screen/model/home_list_entity.dart';
import 'package:flutter_baseui/widgets/gesture_kit.dart';
import 'package:flutter_baseui/widgets/model/icon_event_model.dart';
import 'package:flutter_baseui/widgets/nav_bar_kit.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
  List<HomeListEntity> homeList = [];
  AnimationController? animationController;
  bool multiple = true; // 列表多列视图切换控制

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);

    super.initState();
  }

  @override
  void dispose() {
    animationController?.dispose();
    super.dispose();
  }

  Future<List<HomeListEntity>> _loadData() async {
    homeList.clear();
    await Future<dynamic>.delayed(const Duration(milliseconds: 2000));
    String jsonStr =
        await rootBundle.loadString("lib/assets/mock/homelist.json");
    List<dynamic> list = json.decode(jsonStr) as List<dynamic>;
    for (var item in list) {
      homeList.add(HomeListEntity.fromJson(item as Map<String, dynamic>));
    }
    return homeList;
  }

  Widget homeListView() {
    double height =
        MediaQuery.of(context).padding.top + AppBar().preferredSize.height + 10;
    return GridView(
      padding: EdgeInsets.fromLTRB(10, height, 10, 10),
      physics: const BouncingScrollPhysics(),
      scrollDirection: Axis.vertical,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
        mainAxisSpacing: 10.0,
        crossAxisSpacing: 10.0,
        childAspectRatio: 1.8,
      ),
      children: List<Widget>.generate(homeList.length, (index) {
        int count = homeList.length;
        Animation<double> animation =
            Tween<double>(begin: 0.0, end: 1.0).animate(
          CurvedAnimation(
            parent: animationController!,
            curve:
                Interval((1 / count) * index, 1.0, curve: Curves.fastOutSlowIn),
          ),
        );
        animationController?.forward();
        return homeListItemView(index, animation);
      }),
    );
  }

  Widget homeListItemView(int index, Animation<double> animation) {
    return AnimatedBuilder(
      animation: animationController!,
      builder: (context, child) {
        return FadeTransition(
          opacity: animation,
          child: Transform(
            transform: Matrix4.translationValues(
                0.0, 50 * (1.0 - animation.value), 0.0),
            child: GestureKit(
              borderRadius: BorderRadius.circular(6),
              backgroundColor: Colors.white,
              child: Stack(
                children: [
                  Positioned(
                    right: -140,
                    bottom: -140,
                    child: Image(
                      image: AssetImage(
                          "lib/assets/images/${homeList[index].imageName}.png"),
                    ),
                  ),
                  Positioned(
                    left: -140,
                    top: -80,
                    child: Image(
                      image: AssetImage(
                          "lib/assets/images/${homeList[index].imageName}.png"),
                    ),
                  ),
                  Positioned(
                    right: 15,
                    top: 15,
                    child: Text(
                      homeList[index].title as String,
                      style: const TextStyle(
                        color: Colors.black,
                        fontSize: 40,
                        fontFamily: 'Hanyi',
                      ),
                    ),
                  ),
                  Positioned(
                    left: 15,
                    bottom: 15,
                    child: Text(
                      homeList[index].subTitle as String,
                      style: const TextStyle(
                        color: Colors.black,
                        fontSize: 26,
                        fontFamily: 'Monaco',
                      ),
                    ),
                  )
                ],
              ),
              onTap: () {
                var n = homeList[index].navigation;
                if (n != null && n != '') {
                  FluroNaviagtor.push(context, n);
                }
              },
            ),
          ),
        );
      },
    );
  }

  Widget homeListLoadingView() {
    return const Center(
      child: Text('暂无数据'),
    );
  }

  void appBarRightTap() {
    debugPrint('======111');
  }

  Widget appBar() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      height: ScreenUtil.navBarHeight(context),
      child: NavBarKit(
        title: 'FlutterBaseUI',
        rightConfig: IconEventModel(
          icon: const Icon(Icons.view_agenda),
          onTap: appBarRightTap,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFEDF0F2),
      body: SafeArea(
        top: false,
        bottom: false,
        child: Stack(
          children: [
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              child: FutureBuilder(
                future: _loadData(),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return homeListView();
                  } else {
                    return homeListLoadingView();
                  }
                },
              ),
            ),
            appBar(),
          ],
        ),
      ),
    );
  }
}
